<template>
  <div>
    <div class="nav">
      <van-nav-bar
        title="客服小乐"
        @click-left="onClickLeft"
        left-text="返回"
        left-arrow
      >
        <template #right>
          <van-icon size="26" name="ellipsis" />
        </template>
      </van-nav-bar>
    </div>
    <!-- @click="mainclik" -->
    <div class="main" ref="wrapper" @click="mainclik" id="mainbox">
      <div>
        <div v-for="(item, index) in msgList" :key="index">
          <!-- 这是左边消息 -->
          <div class="left msg" v-if="item.id == receiveid">
            <!-- 头像 -->
            <img
              class="herdimg"
              @load="imgload"
              :src="iconUrl + item.userImage"
            />
            <!-- end头像 -->
            <!-- 左边聊天内容 -->
            <div class="nr">
              <!-- 个性气泡显示 -->
              <div v-if="totype == '个性'">
                <div
                  :style="{
                    background: 'url(' + BubbleUrl + toBubble + ') no-repeat',

                    color: toBubbleColor,
                    'border-radius': 0,
                    'line-height': '25px',
                    transform: 'rotateY(-180deg)',
                  }"
                  class="neir gexin"
                  v-if="item.textType == '文字'"
                >
                  <p
                    style="
                      line-height: 19px;
                      margin-top: 14px;
                      transform: rotateY(-180deg);
                      margin-right: -25px;
                    "
                  >
                    {{ Decode(item.msg) }}
                  </p>
                </div>
              </div>
              <!-- end个性气泡显示 -->
              <!-- 渐变气泡显示 -->
              <div v-else-if="totype == '渐变'">
                <div
                  :style="{
                    backgroundImage:
                      'url(' +
                      (BubbleUrl + toBubble ? BubbleUrl + toBubble : '') +
                      ') !important',
                    backgroundSize: '100% 100%',
                    color: toBubbleColor,
                  }"
                  class="neir"
                  v-if="item.textType == '文字'"
                >
                  <p>{{ Decode(item.msg) }}</p>
                </div>
              </div>
              <!-- end渐变气泡显示 -->

              <!-- 没有气泡 -->
              <div v-else>
                <div class="neir" v-if="item.textType == '文字'">
                  <p>{{ Decode(item.msg) }}</p>
                </div>
              </div>
              <!-- end没有气泡 -->

              <!-- 发送图片 -->
              <div class="textimg" v-if="item.textType == '图片'">
                <img
                  class="imgt"
                  @load="imgload"
                  @click="imgsShow(Decode(item.msg))"
                  :src="Chatvoice + Decode(item.msg)"
                  alt=""
                />
              </div>
              <!-- end发送图片 -->

              <!-- 分享内容 -->
              <div class="Share_item" v-if="item.textType == '分享'">
                <router-link
                  :to="{ name: 'details', params: { gid: item.goodsID } }"
                >
                  <van-card
                    :price="item.GoodsPrice + '.00'"
                    :title="Decode(item.msg)"
                    :thumb="imgUrl + item.GoodsPic"
                  >
                  </van-card>
                </router-link>
              </div>
              <!-- end分享内容 -->
              <!-- 发送好友名片 -->
              <div class="per_crad" v-if="item.textType == '名片'">
                <div class="per_img">
                  <img :src="iconUrl + item.cardPic" alt="" />
                </div>
                <p>{{ Decode(item.msg) }}</p>
              </div>
              <!-- end发送好友名片 -->

              <!-- 语音发送 -->
              <div
                class="neir"
                @click="maddelListening(item, index)"
                v-if="item.textType == '音频'"
              >
                <div :style="{ width: Decode(item.msg) * 5 + 'px' }">
                  <img
                    src="../../assets/icon/iconVoice.png"
                    class="voice-img"
                    alt=""
                  />
                  <p class="timeout">{{ Decode(item.msg) }}″</p>

                  <audio id="musicfx" :ref="'middle' + index">
                    <source :src="Chatvoice + item.Audio" type="audio/mpeg" />
                  </audio>
                </div>
              </div>
              <!-- end语音发送 -->
              <!-- 文件发送 -->
              <div class="fliebox" v-if="item.textType == '文件'">
                <div class="dowdiv" @click.once="Download(Decode(item.msg))">
                  <img
                    src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/fileicon.png"
                    alt=""
                  />
                  <div class="flieleft">
                    <p>{{ Decode(item.msg) }}</p>
                    <p class="kbsize">{{ sizefile(item.fileSize) }}/已接收</p>
                  </div>
                </div>
              </div>
              <!-- end文件发送 -->

              <!-- 红包发送 -->
              <div
                class="redBox"
                @click="openBoxCover(item)"
                v-if="item.textType == '红包'"
              >
                <p>{{ Decode(item.msg) }}</p>
                <span>红包</span>
              </div>
              <div class="desc_linqu" v-if="item.textType == '红包'">
                {{ item.left_tipmsg }}
              </div>

              <!-- end红包发送 -->

              <div class="nt" v-if="item.textType != '红包'">
                {{ changetime(item.dateTime) }}
              </div>
            </div>
            <!-- edn左边聊天内容 -->
          </div>
          <!-- END 这是左边消息 -->

          <!-- 这是右边消息 -->
          <div class="right msg" v-if="item.receive_id == receiveid">
            <!-- 头像 -->
            <img
              class="herdimg"
              @load="imgload"
              :src="iconUrl + item.userImage"
            />
            <!-- end头像 -->
            <!-- 右边聊天内容 -->
            <div class="nr">
              <!-- 个性气泡显示 -->
              <div v-if="Selftype == '个性'">
                <div
                  :style="{
                    background: 'url(' + BubbleUrl + SelfBubble + ') no-repeat',

                    color: SelfBubbleColor,
                    'border-radius': 0,
                    'line-height': '25px',
                  }"
                  class="neir gexin"
                  v-if="item.textType == '文字'"
                >
                  <p
                    style="
                      line-height: 19px;
                      margin-top: 14px;
                      margin-right: -25px;
                    "
                  >
                    {{ Decode(item.msg) }}
                  </p>
                </div>
              </div>
              <!-- end个性气泡显示 -->

              <!-- 渐变气泡显示 -->
              <div v-else-if="Selftype == '渐变'">
                <div
                  :style="{
                    backgroundImage:
                      'url(' + BubbleUrl + SelfBubble + ') !important',
                    backgroundSize: size,
                    color: SelfBubbleColor,
                  }"
                  class="neir"
                  v-if="item.textType == '文字'"
                >
                  <p>{{ Decode(item.msg) }}</p>
                </div>
              </div>
              <!-- end渐变气泡显示 -->
              <!-- 没有气泡 -->
              <div v-else>
                <div class="neir" v-if="item.textType == '文字'">
                  <p>{{ Decode(item.msg) }}</p>
                </div>
              </div>
              <!-- end没有气泡 -->

              <!-- 图片分享 -->
              <div class="textimg" v-if="item.textType == '图片'">
                <img
                  class="imgt"
                  @load="imgload"
                  @click="imgsShow(Decode(item.msg))"
                  :src="Chatvoice + Decode(item.msg)"
                  alt=""
                />
              </div>
              <!-- end图片分享 -->

              <!-- 分享商品内容 -->
              <div class="Share_item" v-if="item.textType == '分享'">
                <router-link
                  :to="{ name: 'details', params: { gid: item.goodsID } }"
                >
                  <van-card
                    :price="item.GoodsPrice + '.00'"
                    :title="Decode(item.msg)"
                    :thumb="imgUrl + item.GoodsPic"
                  >
                  </van-card>
                </router-link>
              </div>
              <!-- end分享商品内容 -->
              <!-- 发送好友名片 -->
              <div class="per_crad" v-if="item.textType == '名片'">
                <div class="per_img">
                  <img :src="iconUrl + item.cardPic" alt="" />
                </div>
                <p>{{ Decode(item.msg) }}</p>
              </div>
              <!-- end发送好友名片 -->
              <!-- 语音发送 -->
              <div
                class="neir"
                @click="maddelListening(item, index)"
                v-if="item.textType == '音频'"
              >
                <div :style="{ width: Decode(item.msg) * 5 + 'px' }">
                  <img
                    src="../../assets/icon/iconVoice.png"
                    class="voice-img"
                    alt=""
                  />
                  <p class="timeout">{{ Decode(item.msg) }}″</p>

                  <audio id="musicfx" :ref="'middle' + index">
                    <source :src="Chatvoice + item.Audio" type="audio/mpeg" />
                  </audio>
                </div>
              </div>
              <!-- end语音发送 -->
              <!-- 文件发送 -->
              <div class="fliebox" v-if="item.textType == '文件'">
                <img
                  src="	https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/fileicon.png"
                  alt=""
                />
                <div class="flieleft">
                  <p>{{ Decode(item.msg) }}</p>
                  <p class="kbsize">{{ sizefile(item.fileSize) }}/已发送</p>
                </div>
              </div>
              <!-- end文件发送 -->
              <!-- 红包发送 -->
              <div
                class="redBox"
                @click="openself(item)"
                v-if="item.textType == '红包'"
              >
                <p>{{ Decode(item.msg) }}</p>
                <span>红包</span>
              </div>
              <div class="desc_linqu" v-if="item.textType == '红包'">
                {{ item.right_tipmsg }}
              </div>
              <!-- <div v-if="item.textType == '红包'">
                {{ changetime(item.dateTime) }}
              </div> -->
              <!-- end红包发送 -->
              <div class="nt" v-if="item.textType != '红包'">
                {{ changetime(item.dateTime) }}
              </div>
            </div>

            <!-- END 右边聊天内容 -->
          </div>
          <!-- END 这是右边消息 -->
        </div>
      </div>
    </div>

    <!-- //输入框 -->
    <div class="send">
      <div>
        <img :src="toc" @click="records" class="Sound" alt="" />
      </div>
      <textarea
        id="emojiInput"
        ref="texttemplate"
        v-model="emojitext"
        :auto-size="{ minRows: 6, maxRows: 15 }"
        allow-clear
        @keyup.enter="handleSend"
        class="chat-send"
        v-if="text1Show"
      />

      <img
        @click="handleSend"
        v-if="text1Show"
        class="sendimg"
        src="../../assets/images/send.png"
      />
      <div
        @touchstart="gotouchstart"
        @touchend="gotouchend"
        class="TextEnter"
        v-else
      >
        按住说话
      </div>

      <div>
        <img
          @click="showToolschange"
          src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/jiaicon.png"
          class="emjonBtn emjonadd"
          alt=""
        />
        <img
          src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/biaoqing.png"
          @click="showEmojinchange"
          class="emjonBtntoll emjonBtn"
          alt=""
        />
      </div>
      <transition name="van-slide-up">
        <div class="Picker" v-if="showTools">
          <van-grid :border="false" :column-num="4">
            <van-grid-item>
              <van-uploader :after-read="afterRead" :before-read="beforeRead">
                <van-image
                  class="tollimg"
                  src="	https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/chatimg.png"
                />
              </van-uploader>

              <p style="margin-top: 10px">发送图片</p>
            </van-grid-item>

            <van-grid-item>
              <van-uploader
                :after-read="afterReadFile"
                accept=".pdf,.doc.,rar,.zip,.docx"
              >
                <van-image
                  class="tollimg"
                  src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/Fileimg.png"
                />
              </van-uploader>

              <p style="margin-top: 10px">文件发送</p>
            </van-grid-item>
            <van-grid-item @click="sendTored">
              <van-image
                class="tollimg"
                src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/redBox_icon.png"
              />
              <p style="margin-top: 10px">红包</p>
            </van-grid-item>
            <van-grid-item @click="openCommoditybox">
              <van-image
                class="tollimg"
                src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/ShareImg.png"
              />
              <p style="margin-top: 10px">分享</p>
            </van-grid-item>
            <van-grid-item @click="Sharecard">
              <van-image
                class="tollimg"
                src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/Businesscard.png"
              />
              <p style="margin-top: 10px">个人名片</p>
            </van-grid-item>
          </van-grid>
        </div>
      </transition>
      <transition name="van-slide-up">
        <div class="Picker" v-if="showEmojin">
          <VEmojiPicker
            style="width: 100%; height: 450px; margin-top: 5px"
            @select="selectEmoji"
          />
        </div>
      </transition>
    </div>
    <van-image-preview v-model="Imageshow" :images="images">
    </van-image-preview>
    <!-- 分享自己买过的商品 -->
    <van-popup
      v-model="popupshow"
      round
      position="bottom"
      :style="{ height: '90%' }"
    >
      <van-cell v-for="item in goodsList" clickable :key="item.orderID">
        <template #title>
          <div class="titel_left">
            <lazy-component style="width: 90px; height: 41px">
              <img v-lazy="item.GoodsPic" alt="" />
            </lazy-component>

            <div class="name_l">
              <p>{{ item.GoodName }}</p>
              <p class="price">￥{{ item.GoodsPrice }}.00</p>
            </div>
          </div>
        </template>
        <template #right-icon>
          <van-button
            class="btnadd"
            @click.self="onShare(item)"
            round
            type="info"
            >分享</van-button
          >
        </template>
      </van-cell>
    </van-popup>
    <!-- end分享自己买过的商品 -->
    <!-- 好友列表弹框 -->
    <van-popup
      v-model="Fridepopupshow"
      round
      position="bottom"
      :style="{ height: '90%' }"
    >
      <van-cell v-for="item in friendslist" :key="item.listID">
        <template #title>
          <div class="left-item">
            <img :src="iconUrl + item.userImage" alt="" />
            <p>{{ item.user }}</p>
          </div>
        </template>
        <template #right-icon>
          <div>
            <van-button
              class="btnadd"
              @click="onShareCard(item)"
              round
              type="info"
              >发送</van-button
            >
          </div>
        </template>
      </van-cell>
    </van-popup>
    <!-- end好友列表弹框 -->
    <!-- 输入语音的遮罩层 -->
    <van-overlay :show="overlayshow" @click="overlayshow = false">
      <div class="wrapper" @click.stop>
        <div class="block">
          <img
            src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/microphone.gif"
            alt=""
          />
        </div>
      </div>
    </van-overlay>
    <!-- end输入语音的遮罩层 -->
    <!-- 红包遮罩 -->
    <van-overlay z-index="9999" :show="overlayRedboxshow">
      <div class="wrapper" @click.stop>
        <div class="redcover">
          <img
            src="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/Redenvelope_Cover.png"
            alt=""
          />
          <div @click="overlayRedboxshow = false" class="cloicon">
            <van-icon name="close" />
          </div>
          <div class="renName">
            <img :src="iconUrl + renbox_img" alt="" />
            <p>{{ renbox_name }}的红包</p>
          </div>
          <div class="titlemsg">{{ Decode(renbox_msg) }}</div>
          <div class="openred" @click="toRedpaker"></div>
        </div>
      </div>
    </van-overlay>
    <!-- end红包遮罩 -->
  </div>
</template>
<script>
import { upload } from "../../utils/Fileupload";

import Recorder from "js-audio-recorder";
const lamejs = require("lamejs");
const recorder = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 48000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1, // 声道，支持 1 或 2， 默认是1
  // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
});
import BScroll from "@better-scroll/core";
import { mapState } from "vuex";
import myfun from "../../utils/timeDate.js";
let Base64 = require("js-base64").Base64; //用于字符串编码 解码 用来存储表情
// const ws = new WebSocket("ws://localhost:8060");
const ws = new WebSocket("ws://106.55.48.147:8060");

export default {
  data() {
    return {
      renbox_name: "",
      renbox_img: "",
      renbox_msg: "",
      redbox_price: "",
      overlayRedboxshow: false,
      overlayshow: false,
      text1Show: true,
      toc: "https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/shengbo.png",
      emojitext: "",
      list: "",
      userName: "",
      msgList: [],
      showEmojin: false,
      showTools: false,
      SelfBubble: "",
      toBubble: "",
      toBubbleColor: "",
      SelfBubbleColor: "",
      Selftype: "",
      totype: "",
      Imageshow: false,
      images: [],
      size: "",
      popupshow: false,
      goodsList: [],
      Fridepopupshow: false,
      friendslist: [],
      timer: null,
      redtime: "",
    };
  },
  updated() {
    try {
      this.scroll.scrollTo(0, this.scroll.maxScrollY); //页面运行让其滚动到底部
    } catch (error) {}
  },
  mounted() {
    this.initBScroll();
    this.getgetPrivatInfo();
    this.userName = this.emailLogin[0].Nickname;
    //注册websocket的几个方法
    ws.addEventListener("open", this.handleWsOpen.bind(this), false);
    ws.addEventListener("close", this.handleWsClose.bind(this), false);
    ws.addEventListener("error", this.handleWsError.bind(this), false);
    ws.addEventListener("message", this.handleWsMessage.bind(this), false); //介绍信息对策方法
  },
  created() {
    this.getgetPrivatInfo();
  },
  activated() {
    this.scroll.refresh();

    this.scroll.scrollTo(0, this.scroll.maxScrollY);
    this.getgetPrivatInfo();
    this.size = "100% 100%";
    this.getqueryBubble();
  },

  computed: {
    ...mapState(["emailLogin"]),
    receiveid() {
      return this.$store.state.friID; //获取对方的id
    },
    chatUser() {
      return this.$store.state.chatName; //获取对方的用户名
    },
  },
  watch: {
    receiveid() {
      //监听对方id的改变从而刷新数据
      this.getgetPrivatInfo();
      // this.getqueryBubble();
    },
    msgList() {
      this.$nextTick(() => {
        this.scroll.refresh();
        this.scroll.scrollTo(0, this.scroll.maxScrollY);
      });
    },
  },
  methods: {
    sizefile(limit) {
      var size = "";
      if (limit < 0.1 * 1024) {
        //如果小于0.1KB转化成B
        size = limit.toFixed(2) + "B";
      } else if (limit < 0.1 * 1024 * 1024) {
        //如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + "KB";
      } else if (limit < 0.1 * 1024 * 1024 * 1024) {
        //如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
      } else {
        //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      var sizestr = size + "";
      var len = sizestr.indexOf(".");
      var dec = sizestr.substr(len + 1, 2);
      if (dec == "00") {
        //当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
      }
      return sizestr;
    },
    imgload() {
      this.scroll.refresh();
    },
    // 绑定BScroll
    initBScroll() {
      this.scroll = new BScroll(this.$refs.wrapper, {
        mouseWheel: true,
        click: true,
        tap: true,
      });
    },
    refresh() {
      this.scroll && this.scroll.refresh();
    },
    //上传照片的前置处理 判断是不是照片
    beforeRead(file) {
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$toast("请上传图片");
        return false;
      }
      return true;
    },

    //发送图片的方法
    afterRead(file) {
      var that = this;
      let url = "Chatvoice";
      upload.uploadChange(file, url);

      let umsg = {
        id: that.emailLogin[0].userID,
        receive_id: that.receiveid,
        user: that.emailLogin[0].Nickname,
        userImage: that.emailLogin[0].userImg,
        dateTime: new Date(),
        msg: Base64.encode(file.file.name),
        msgType: 2,
        textType: "图片",
      };
      let dataChat = {
        id: that.emailLogin[0].userID,
        receive_id: that.receiveid,
        user: that.emailLogin[0].Nickname,
        dateTime: new Date(),
        userImage: that.emailLogin[0].userImg,
        msg: Base64.encode(file.file.name),
        msgType: 2,
        textType: "图片",
      };

      let lastmsg = {
        dateTime: new Date(),
        msg: Base64.encode("[图片]"),
        receive_id: that.receiveid,
        uid: that.emailLogin[0].userID,
      };
      this.$nextTick(() => {
        console.log(this.scroll.maxScrollY);
        this.scroll.scrollTo(0, this.scroll.maxScrollY);
      });
      that.showTools = false;
      setTimeout(() => {
        ws.send(
          //发送消息
          JSON.stringify({
            id: that.emailLogin[0].userID,
            receive_id: that.receiveid,
            user: that.emailLogin[0].Nickname,
            dateTime: new Date(),
            userImage: that.emailLogin[0].userImg,
            msg: Base64.encode(file.file.name),
            msgType: 2,
            textType: "图片",
          })
        );
        that.addmsgImg(dataChat, lastmsg);
        that.msgList.push(umsg); //push静态数据到数组中 显示
      }, 600);
      //发送图片后定位的该图片的位置
    },
    //发送文件
    afterReadFile(file) {
      let url = "file";
      const fileList = upload.uploadChange(file, url);
      ws.send(
        //发送消息
        JSON.stringify({
          id: this.emailLogin[0].userID,
          receive_id: this.receiveid,
          user: this.emailLogin[0].Nickname,
          dateTime: new Date(),
          userImage: this.emailLogin[0].userImg,
          msg: Base64.encode(file.file.name),
          fileSize: file.file.size,
          msgType: 9,
          textType: "文件",
        })
      );
      let msg = {
        id: this.emailLogin[0].userID,
        receive_id: this.receiveid,
        user: this.emailLogin[0].Nickname,
        dateTime: new Date(),
        userImage: this.emailLogin[0].userImg,
        msg: Base64.encode(file.file.name),
        fileSize: file.file.size,
        msgType: 9,
        textType: "文件",
      };
      let lastmsg = {
        dateTime: new Date(),
        msg: Base64.encode("[文件]"),
        receive_id: this.receiveid,
        uid: this.emailLogin[0].userID,
      };
      this.addmsgImg(msg, lastmsg);
      this.showTools = false;
      this.msgList.push(msg);
      this.$nextTick(() => {
        this.scroll.scrollTo(0, this.scroll.maxScrollY);
      });
    },
    //下载文件\
    Download(item) {
      upload.DownloadFile(item);
    },
    //新增聊天记录
    async addmsgImg(obj, obj2) {
      //新增聊天记录
      const { data: res } = await this.$http.post("addPrivatechat", obj);
      const { data: res1 } = await this.$http.post("UpdateLatestMsg", obj2);
      console.log(res);
    },
    //表情显示 和工具栏显示
    showToolschange() {
      this.showTools = true;
      this.showEmojin = false;
    },
    //表情显示 和工具栏显示
    showEmojinchange() {
      this.showEmojin = true;
      this.showTools = false;
      this.text1Show = true;
    },
    mainclik() {
      this.showEmojin = false;
      this.showTools = false;
    },
    //websocket连接后边向后端发送自己的id用来进行私聊
    getUid() {
      ws.send(JSON.stringify({ uid: this.emailLogin[0].userID }));
    },
    //事件格式化处理
    changetime(t) {
      return myfun.dateTime1(t);
    },
    //表情文字消息解码处理
    Decode(t) {
      return Base64.decode(t);
    },
    onClickLeft() {
      this.$router.push("/Message");
      this.showEmojin = false;
      this.showTools = false;
    },
    //获取聊天记录
    async getgetPrivatInfo() {
      try {
        const { data: res } = await this.$http.get("getPrivatInfo", {
          params: {
            uid: this.emailLogin[0].userID,
            receive_id: this.receiveid,
            receive_id2: this.receiveid,
            uid2: this.emailLogin[0].userID,
          },
        });
        this.msgList = res.data.concat(res.data2);

        this.msgList.sort((x, y) => {
          return x.dateTime < y.dateTime ? -1 : 1;
        });
      } catch (error) {}
    },
    //获取聊天自己的气泡和对方的气泡
    async getqueryBubble() {
      try {
        const { data: res } = await this.$http.get("queryBubble", {
          params: {
            uid: this.emailLogin[0].userID,
            receive_id: this.receiveid,
            receive_id2: this.receiveid,
            uid2: this.emailLogin[0].userID,
          },
        });

        this.SelfBubble = res.data[0].Bubble;
        this.SelfBubbleColor = res.data[0].bubbleColor;
        this.Selftype = res.data[0].bubbleType;
        this.toBubble = res.data2[0].Bubble;
        this.toBubbleColor = res.data2[0].bubbleColor;
        this.totype = res.data2[0].bubbleType;
      } catch (error) {}
    },
    //图片预览
    imgsShow(item) {
      this.images = [];
      this.images.push(this.Chatvoice + item);
      this.Imageshow = true;
    },
    // 分享内容跳转
    todetalis() {
      console.log("dasdas");
    },
    //发送消息
    async handleSend() {
      const msg = this.msg;
      let umsg = {
        id: this.emailLogin[0].userID,
        receive_id: this.receiveid,
        user: this.emailLogin[0].Nickname,
        userImage: this.emailLogin[0].userImg,
        dateTime: new Date(),
        msg: Base64.encode(this.emojitext),
        msgType: 2, //代表私聊消息
        textType: "文字",
      };
      ws.send(
        JSON.stringify({
          id: this.emailLogin[0].userID,
          receive_id: this.receiveid,
          user: this.emailLogin[0].Nickname,
          dateTime: new Date(),
          userImage: this.emailLogin[0].userImg,
          msg: Base64.encode(this.emojitext),
          msgType: 2,
          textType: "文字",
        })
      );

      let dataChat = {
        id: this.emailLogin[0].userID,
        receive_id: this.receiveid,
        user: this.emailLogin[0].Nickname,
        dateTime: new Date(),
        userImage: this.emailLogin[0].userImg,
        msg: Base64.encode(this.emojitext),
        msgType: 2,
        textType: "文字",
      };
      let lastmsg = {
        dateTime: new Date(),
        msg: Base64.encode(this.emojitext),
        receive_id: this.receiveid,
        uid: this.emailLogin[0].userID,
      };
      try {
        this.scroll.scrollTo(0, this.scroll.maxScrollY);
      } catch (error) {}

      // document.getElementById("sendbox").scrollIntoView();
      const { data: res } = await this.$http.post("/addPrivatechat", dataChat);
      // console.log(res);
      const { data: res1 } = await this.$http.post("/UpdateLatestMsg", lastmsg);

      this.msgList.push(umsg);
      this.getgetPrivatInfo();
      this.emojitext = "";
      this.showEmojin = false;
    },
    //表情选择
    selectEmoji(emoji) {
      var elInput = document.getElementById("emojiInput"); //获取输入框元素
      // console.log(elInput);
      var start = elInput.selectionStart; // 记录光标开始的位置
      var end = elInput.selectionEnd; // 记录选中的字符 最后的字符的位置
      if (start === undefined || end === undefined) return;
      var txt = elInput.value;
      // 将表情添加到选中的光标位置
      var result = txt.substring(0, start) + emoji.data + txt.substring(end);
      elInput.value = result; // 赋值给input的value
      // 重置光标位置
      elInput.focus();
      elInput.selectionStart = start + emoji.data.length;
      elInput.selectionEnd = start + emoji.data.length;

      this.emojitext = result; // 赋值(注意这里一定要赋值给表情输入框绑定的那个值)
    },
    //打开已经买过的商品列表 并获取商品数据
    openCommoditybox() {
      this.popupshow = true;
      this.getPurchasedBefore();
    },
    //获取购买过的商品
    async getPurchasedBefore() {
      const { data: res } = await this.$http.get("getPurchasedBefore", {
        params: { id: this.emailLogin[0].userID },
      });
      this.goodsList = res.data;
    },
    //给好友分享我买过的商品
    async onShare(item) {
      let proImg = item.GoodsPic.substring(item.GoodsPic.lastIndexOf("/") + 1);
      this.popupshow = false;
      let msg = {
        id: this.emailLogin[0].userID,
        receive_id: this.receiveid,
        user: this.emailLogin[0].Nickname,
        dateTime: new Date(),
        userImage: this.emailLogin[0].userImg,
        msg: Base64.encode(item.GoodName),
        goodsID: item.GoodsID,
        GoodsPic: proImg,
        GoodsPrice: item.GoodsPrice,
        msgType: 6,
        textType: "分享",
      };
      ws.send(
        //发送消息
        JSON.stringify({
          id: this.emailLogin[0].userID,
          receive_id: this.receiveid,
          user: this.emailLogin[0].Nickname,
          dateTime: new Date(),
          userImage: this.emailLogin[0].userImg,
          msg: Base64.encode(item.GoodName),
          goodsID: item.GoodsID,
          GoodsPic: proImg,
          GoodsPrice: item.GoodsPrice,
          msgType: 6,
          textType: "分享",
        })
      );
      this.msgList.push(msg);
      this.showEmojin = false;
      this.showTools = false;
      let Newmsg = {
        dateTime: new Date(),
        msg: Base64.encode(item.GoodName),
        receive_id: this.receiveid,
        uid: this.emailLogin[0].userID,
      };
      const { data: res } = await this.$http.post("addPrivatechat", msg); //新增私聊信息
      const { data: res1 } = await this.$http.post("UpdateLatestMsg", Newmsg);
    },
    //打开好友列表框
    Sharecard() {
      this.Fridepopupshow = true;
      this.getfriendslist();
    },
    //获取好友列表
    async getfriendslist() {
      const { data: res } = await this.$http.get("getFriendList", {
        params: { id: this.emailLogin[0].userID },
      });
      this.friendslist = res.data;
    },
    //切换输入方式
    records() {
      if (this.text1Show) {
        this.text1Show = false;
        this.showEmojin = false;
        this.showTools = false;
        this.toc =
          "https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/jiangpan.png";
      } else {
        this.text1Show = true;
        this.toc =
          "https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/shengbo.png";
      }
    },
    //长按录音
    gotouchstart() {
      let i = 0;
      this.overlayshow = true;
      this.timer = setInterval(() => {
        i++;
        console.log(i);
        if (i >= 60) {
          this.$toast("录制时间太长了!");
          this.overlayshow = false;
          recorder.stop();
          clearInterval(this.timer);
        }
      }, 1000);
      recorder.start();
    },
    //手指离开录音结束
    gotouchend() {
      let _this = this;
      clearInterval(this.timer);

      _this.overlayshow = false;
      recorder.stop();
      let duration = parseInt(recorder.duration);

      if (duration < 1) {
        this.$toast("录制时间小于一秒！");
      } else {
        const mp3Blob = this.convertToMp3(recorder.getWAV());
        var formData = new FormData();
        var fileOfBlob = new File([mp3Blob], new Date().getTime() + ".mp3", {
          type: "audio/mp3",
        });
        console.log(fileOfBlob);
        formData.append("test", fileOfBlob);
        let url = "Chatvoice";
        upload.uploadChangeHeard(fileOfBlob, url);

        let msg = {
          id: _this.emailLogin[0].userID,
          receive_id: _this.receiveid,
          user: _this.emailLogin[0].Nickname,
          dateTime: new Date(),
          userImage: _this.emailLogin[0].userImg,
          msg: Base64.encode(duration),
          Audio: fileOfBlob.name,
          msgType: 8,
          textType: "音频",
        };

        let lastmsg = {
          dateTime: new Date(),
          msg: Base64.encode("[语音]"),
          receive_id: _this.receiveid,
          uid: _this.emailLogin[0].userID,
        };

        setTimeout(() => {
          ws.send(
            //发送消息
            JSON.stringify({
              id: _this.emailLogin[0].userID,
              receive_id: _this.receiveid,
              user: _this.emailLogin[0].Nickname,
              dateTime: new Date(),
              userImage: _this.emailLogin[0].userImg,
              msg: Base64.encode(duration),
              Audio: fileOfBlob.name,
              msgType: 8,
              textType: "音频",
            })
          );
          _this.addmsgImg(msg, lastmsg);
          _this.msgList.push(msg);
        }, 600);
        this.$nextTick(() => {
          this.scroll.scrollTo(0, this.scroll.maxScrollY);
        });
      }
    },
    //播放语音
    maddelListening(item, index) {
      var middle = "middle" + index;
      middle = this.$refs[middle][0];
      if (middle.paused) {
        middle.play();
      } else {
        middle.pause();
      }
    },
    //录音格式转换
    convertToMp3(wavDataView) {
      // 获取wav头信息
      const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
      const { channels, sampleRate } = wav;
      const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
      // 获取左右通道数据
      const result = recorder.getChannelData();
      const buffer = [];

      const leftData =
        result.left &&
        new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
      const rightData =
        result.right &&
        new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
      const remaining = leftData.length + (rightData ? rightData.length : 0);

      const maxSamples = 1152;
      for (let i = 0; i < remaining; i += maxSamples) {
        const left = leftData.subarray(i, i + maxSamples);
        let right = null;
        let mp3buf = null;

        if (channels === 2) {
          right = rightData.subarray(i, i + maxSamples);
          mp3buf = mp3enc.encodeBuffer(left, right);
        } else {
          mp3buf = mp3enc.encodeBuffer(left);
        }

        if (mp3buf.length > 0) {
          buffer.push(mp3buf);
        }
      }

      const enc = mp3enc.flush();

      if (enc.length > 0) {
        buffer.push(enc);
      }

      return new Blob(buffer, { type: "audio/mp3" });
    },
    //发送名片
    async onShareCard(item) {
      ws.send(
        //发送消息
        JSON.stringify({
          id: this.emailLogin[0].userID,
          receive_id: this.receiveid,
          user: this.emailLogin[0].Nickname,
          dateTime: new Date(),
          userImage: this.emailLogin[0].userImg,
          msg: Base64.encode(item.user),
          cardID: item.id,
          cardPic: item.userImage,
          msgType: 7,
          textType: "名片",
        })
      );
      let msg = {
        id: this.emailLogin[0].userID,
        receive_id: this.receiveid,
        user: this.emailLogin[0].Nickname,
        dateTime: new Date(),
        userImage: this.emailLogin[0].userImg,
        msg: Base64.encode(item.user),
        cardID: item.id,
        cardPic: item.userImage,
        msgType: 7,
        textType: "名片",
      };
      this.msgList.push(msg);
      this.showEmojin = false;
      this.showTools = false;
      this.Fridepopupshow = false;
      let Newmsg = {
        dateTime: new Date(),
        msg: Base64.encode(item.user),
        receive_id: this.receiveid,
        uid: this.emailLogin[0].userID,
      };
      const { data: res } = await this.$http.post("addPrivatechat", msg); //新增私聊信息
      const { data: res1 } = await this.$http.post("UpdateLatestMsg", Newmsg);
    },
    //跳转至红包输入金额界面
    sendTored() {
      this.$store.commit("setfriID", this.receiveid);
      this.$store.commit("setchatName", this.chatUser);
      this.showTools = false;
      this.$router.push("/AmountInput");
    },
    //打开红宝
    openBoxCover(item) {
      console.log(item.isOpen);
      if (item.isOpen === "false") {
        this.redbox_price = item.red_amount;
        this.redtime = item.dateTime;
        this.queryRedPackage(item.dateTime);
        this.$store.commit("setredPackageTime", item.dateTime);
        this.renbox_name = item.user;
        this.renbox_msg = item.msg;
        this.renbox_img = item.userImage;
        this.overlayRedboxshow = true;
      } else {
        this.queryRedPackage(item.dateTime);
        this.$router.push("/DetailsRedenvelopes");
      }
    },
    //打开自己发出的红包
    openself(item) {
      this.queryRedPackage(item.dateTime);
      this.$router.push("/SendRedenvelopes");
    },
    //查看红包
    async queryRedPackage(item) {
      const { data: res } = await this.$http.get("queryRedpaker", {
        params: { time: item },
      });
      this.$store.commit("setredPackageInfo", res.data);
    },
    //跳转到红包详情
    async toRedpaker() {
      const { data: res } = await this.$http.post("redPackerReceived", {
        time: this.redtime,
      });
      this.overlayRedboxshow = false;
      for (let i = 0; i < this.msgList.length; i++) {
        if (this.redtime === this.msgList[i].dateTime) {
          this.msgList[i].left_tipmsg =
            "你领取了" + this.renbox_name + "的红包";
        }
      }
      ws.send(
        //发送消息
        JSON.stringify({
          id: this.emailLogin[0].userID,
          receive_id: this.receiveid,
          user: this.emailLogin[0].Nickname,
          dateTime: new Date(),
          userImage: this.emailLogin[0].userImg,
          left_tipmsg: "你领取了" + this.emailLogin[0].Nickname + "的红包",
          right_tipmsg: this.emailLogin[0].Nickname + "领取了你的红包",
          date: this.redtime,
          msgType: 11,
        })
      );
      let damsg = {
        left_tipmsg: "你领取了" + this.renbox_name + "的红包",
        right_tipmsg: this.emailLogin[0].Nickname + "领取了你的红包",
        time: this.redtime,
      };
      const { data: res1 } = await this.$http.post(
        "RedenvelopeReception",
        damsg
      );
      //收到红包金额增加
      const { data: res3 } = await this.$http.post("NewAmount", {
        price: this.redbox_price,
        uid: this.emailLogin[0].userID,
      });
      this.addConsumptionInfo();
      this.$router.push("/DetailsRedenvelopes");
    },
    //增加消费收益
    async addConsumptionInfo() {
      let data = {
        conType: "红包-收益",
        time: new Date(),
        Expenditure: 0,
        Benefit: this.redbox_price,
        typeIcon:
          "https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/zhichu_redbox.png",
        userID: this.emailLogin[0].userID,
      };
      const { data: res } = await this.$http.post("addConsumptionInfo", data);
      console.log(res);
    },
    handleWsOpen(e) {
      console.log(e);
      this.getUid();
    },
    handleWsClose(e) {
      console.log("连接关闭：", e);
    },
    handleWsError(e) {
      console.log("连接错误：", e);
    },
    //接收消息
    handleWsMessage(e) {
      let data = JSON.parse(e.data);

      //这里是接收领取红包的消息
      if (data.msgType === 11) {
        for (let i = 0; i < this.msgList.length; i++) {
          if (data.date === this.msgList[i].dateTime) {
            this.msgList[i].right_tipmsg = data.right_tipmsg;
          }
        }
      } else {
        //接收的消息 push到数组中显示
        this.msgList.push(data);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.nav {
  position: fixed;
  left: 0;
  width: 100%;
  z-index: 1200;
}
.main {
  // padding: 40px 0px 0px;
  position: absolute;
  overflow: hidden;
  width: 100%;
  top: 50px;
  left: 0;
  right: 0;
  bottom: 70px;
}
.main,
.modfiy-mian {
  .msg {
    display: flex;

    align-items: flex-end;
    // padding: 4px 0;
    .herdimg {
      flex: none;
      width: 40px;
      height: 40px;
      border-radius: 18px;
      margin: 22px 8px;
    }
    .nr {
      .neir {
        padding: 10px 40px;
        min-height: 20px;
        font-size: 14px;
        color: #ffffff;
        line-height: 20px;
        max-width: 200px;
      }
      .nt {
        font-size: 12px;
        color: rgba(25, 29, 35, 0.5);
        line-height: 25px;
      }
    }
  }
  .left {
    flex-direction: row;
    .neir {
      background: #37bcff;
      border-radius: 24px 24px 24px 0px;
      .voice-img {
        width: 20px !important;
        height: 20px !important;
        float: left !important;

        position: absolute;
        left: 60px;
      }
      .timeout {
        float: right;
        margin-right: -20px;
      }
    }
    .redBox {
      top: 28px;
    }
    .desc_linqu {
      left: 95px;
    }
  }
  .right {
    flex-direction: row-reverse;
    .neir {
      background: #ff985e;
      border-radius: 24px 24px 0px 24px;
      .voice-img {
        width: 20px !important;
        height: 20px !important;
        float: right !important;

        transform: rotate(180deg);
        position: absolute;
        /* left: 10px; */
        right: 63px;
      }
      .timeout {
        float: left;
        margin-left: -30px;
      }
    }
    .redBox {
      top: 20px;
      left: 4px;
      transform: rotateY(180deg);
      p {
        transform: rotateY(180deg);
      }
      span {
        transform: rotateY(180deg);
      }
    }
    .nt {
      margin-left: 3px;
    }
  }
  .center {
    text-align: center;
    margin-top: 20px;
    // text-align: center;
    // padding: 20px 0 2px;
    .inner {
      font-size: 14px;
      display: inline-block;
      color: rgba(25, 29, 35, 0.5);
      line-height: 15px;
    }
  }
}
.gexin {
  background-size: cover !important;
}
.send {
  position: fixed;
  z-index: 1002;
  bottom: 0;
  width: 100%;
  padding-bottom: 10px;
  min-height: 40px;
  background: rgba(255, 255, 255, 0.96);
  display: flex;
  flex-direction: column;

  .chat-send {
    flex: 1;
    /* min-height: 13px; */
    background: #ffffff;
    border-radius: 11px;
    /* font-size: 15px; */
    color: #191d23;
    // line-height: 20px;
    padding: 3px;
    padding-right: 31px;
    width: 230px;
    margin-left: 38px;
  }
  .TextEnter {
    flex: 1;
    /* min-height: 13px; */
    background: #ffffff;
    border-radius: 11px;
    /* font-size: 15px; */
    color: #191d23;
    line-height: 37px;
    padding: 5px;
    padding-right: 31px;
    width: 235px;
    margin-left: 36px;
    border: 1px solid;
    text-align: center;
    -webkit-touch-callout: none;

    -webkit-user-select: none;

    -khtml-user-select: none;

    -moz-user-select: none;

    -ms-user-select: none;

    user-select: none;
  }
  .sendimg {
    width: 25px;
    height: 25px;
    position: absolute;
    right: 75px;
    top: 10px;
  }
}
.modify {
  position: fixed;
  overflow: hidden;
  left: 0;
  bottom: -90%;
  width: 100%;
  height: 90%;
  z-index: 1000;
  background: #fff;
  border-radius: 48px 48px 0px 0px;
}
.u-name {
  position: absolute;
  top: 0;
  background-color: #fff;
  height: 80px;
  text-align: center;
  width: 100%;
  line-height: 80px;
}
.modfiy-mian {
  padding: 88px 28px 120px;
  box-sizing: border-box;
  height: 100%;
}
.bg {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.4);
}
.Picker {
  height: 220px;
}
.emjonBtn {
  position: absolute;
}
.emjonadd {
  width: 32px;
  height: 32px;
  right: 4px;
  top: 8px;
}
.Sound {
  width: 24px;
  height: 24px;
  position: absolute;
  top: 14px;
  // border: 1px solid #474444;
  border-radius: 50%;
  left: 5px;
}
.emjonBtntoll {
  right: 37px;
  width: 27px;
  height: 27px;
  top: 11px;
}
.textimg {
  max-width: 142px;
  max-height: 160px;
  .imgt {
    max-width: 142px !important;
    max-height: 160px !important;
    border-radius: 10px !important;
    margin-left: -1px !important;
    margin-top: 15px;
  }
}
.tollimg {
  padding: 10px;
  width: 25px;
  height: 25px;
  background: #f0f0f0;
  border-radius: 50%;
}
.Share_item {
  border: 1px solid #e6e6e6;
  width: 290px;
  border-radius: 10px;
}
.btnadd {
  width: 60px;
  height: 26px;
  font-size: 14px;
  padding: 0 6px;
  background: #ffe431;
  border: 1px solid #ffe431;
  color: #272832;
  letter-spacing: -0.41px;
  margin-top: 15px;
}
.titel_left {
  display: flex;
  align-items: center;
  img {
    width: 40px;
    height: 40px;
  }
  .name_l {
    margin-left: 11px;
    text-align: left;
    line-height: 21px;
    p {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }
  .price {
    color: #f9410d;
    font-weight: 600;
  }
}
.left-item {
  display: flex;
  align-items: center;

  p {
    font-family: PingFangSC-Regular;
    font-size: 18px;
    color: #272832;
    letter-spacing: -0.62px;
    margin-left: 16px;
  }
  img {
    width: 40px;
    height: 40px;
    border-radius: 10px;
  }
}
.per_crad {
  width: 200px;
  height: 80px;
  background: url(../../assets/icon/Pecards.png) no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  border-radius: 10px;
  .per_img {
    margin-left: 10px;
    img {
      width: 40px;
      height: 40px;
      border: 2px solid white;
      border-radius: 4px !important;
    }
  }
  p {
    color: white;
    margin-left: 10px;
    font-size: 17px;
  }
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90%;
}

.block {
  width: 150px;
  height: 150px;
}
.fliebox {
  max-width: 300px;
  height: 80px;
  display: flex;
  align-items: center;
  border-radius: 10px;
  border: 1px solid #9e9e9e;
  padding: 5px;
  margin-top: 10px;
  .dowdiv {
    display: flex;
  }
  .flieleft {
    margin-left: 10px;
  }
  img {
    width: 40px !important;
    height: 40px !important;
    border-radius: 0 !important;
    margin-left: 5px;
  }
}
.kbsize {
  font-size: 13px;
  color: #b1b1b1;
}
.redBox {
  background: url(https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/Redenvelope.png)
    no-repeat;
  background-size: 100% 100%;
  width: 230px;
  height: 85px;
  position: relative;
  top: 20px;
  left: -6px;
  margin-bottom: 20px;
  p {
    color: white;
    font-size: 16px;
    left: 58px;
    position: absolute;
    top: 20px;
    // font-weight: 600;
  }
  span {
    color: white;
    left: 30px;
    position: absolute;
    top: 55px;
  }
}
.desc_linqu {
  position: absolute;
  // margin-top: 10px;
  /* top: 10px; */
  left: 128px;
  color: #b2b2b2;
  font-size: 13px;
}
.redcover {
  width: 270px;
  height: 450px;
  margin-top: 20px;
  position: relative;
  img {
    width: 100%;
    height: 100%;
  }
  .cloicon {
    color: white;
    position: absolute;
    top: -20px;
    right: -25px;
    color: white;
    i {
      font-size: 25px;
    }
  }
}
.renName {
  position: absolute;
  top: 35px;
  display: flex;
  align-items: center;
  left: 25%;
  img {
    width: 35px;
    height: 35px;
    border-radius: 50%;
  }
  p {
    color: #f7ddaa;
    margin-left: 6px;
  }
}
.titlemsg {
  position: absolute;
  top: 88px;
  display: flex;
  align-items: center;
  left: 18%;
  font-size: 20px;
  color: #eec48c;
  font-weight: 600;
}
.openred {
  width: 80px;
  height: 80px;
  position: absolute;
  top: 45vh;
  left: 34%;
  // border: 1px solid red;
}
</style>